<!-- c_check_detail.ftl 盘点单详情 -->
var CCheckDetail = {
    u: '/cCheckDetail'
    , uList: '/cCheckDetail/list'
    , uEdit: '/cCheckDetail/edit'
    , uDel: '/cCheckDetail/delete'
    , unitArr: []
    , editIndex: -1
    , checkStatus: 0
};
CCheckDetail.checkId = 0;
CCheckDetail.dg = function () {
    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        async: true,
        success: function (data) {
            CCheckDetail.unitArr = data;
        }
    });

    var grid = new $yd.DataGrid(this.dtable);
    // grid.onDblClickRow = function (index,row) {
    //     CCheckDetail._edit(row['id']);
    // };
    grid.rownumbers = true;
    grid.pagination = false;
    grid.url = CCheckDetail.uList + "?checkId=" + CCheckDetail.checkId;
    grid.columns = [[
        {field: 'id', checkbox: false, hidden: true}
        , {field: 'skuId', hidden: true}
        , {field: 'positionId', hidden: true}
        , {field: 'goodsName', title: '商品名称', width: 80}
        , {field: 'skus', title: '规格', width: 100}
        , {field: 'skuCode', title: '商品编号', width: 80}
        , {
            field: 'unit', title: '单位', width: 80, formatter: function (value, row, index) {
                for (var i = 0; i < CCheckDetail.unitArr.length; i++) {
                    if (value == CCheckDetail.unitArr[i].id) {
                        return CCheckDetail.unitArr[i].text;
                    }
                }
                return value;
            }
        }
        , {field: 'positionName', title: '库位', width: 80}
        // , {field: 'batchCode', title: '批次', width: 80}
        , {
            field: 'count', title: '库存数量', width: 80, formatter: function (value, row) {
                if(CCheckDetail.checkStatus != 0) {
                    return value;
                }
                if(Number(value) != Number(row.curNum)) {
                    return value + "（<span style='color:red'>" + row.curNum + "</span>）";
                } else {
                    return value;
                }
            }
        }
        , {field: 'curNum', title: '当前库存数量', width: 80, hidden: true}
        , {
            field: 'checkCount',
            title: '<span style="color:blue">盘点数量</span>',
            width: 80,
            editor: {type: 'numberbox', options: {required: true, min: 0, precision: 0}}
        }
        , {
            field: 'checkTotal', title: '盈亏数量', width: 80, formatter: function (value, row) {
                var result = 0;
                if(CCheckDetail.checkStatus == 0) {
                    result = Number(row['checkCount']) - Number(row['curNum']);
                } else {
                    result = Number(row['checkCount']) - Number(row['count']);
                }
                if (result > 0) {
                    return "<span style='color:blue'>" + result + "</span>"
                } else if (result < 0) {
                    return "<span style='color:red'>" + result + "</span>"
                } else {
                    return result;
                }
            }
        }
        , {field: 'remark', title: '<span style="color:blue">备注</span>', width: 80, editor: {type: 'textbox'}}
    ]];
    grid.onClickCell = function (index, field) {
        if(CCheckDetail.checkStatus != 0) {
            return;
        }
        if (CCheckDetail.editIndex != index) {
            if (CCheckDetail.editIndex > -1) {
                CCheckDetail.dtable.datagrid('endEdit', CCheckDetail.editIndex);
            }
            CCheckDetail.editIndex = index;
        }
        if (field == "checkCount") {
            CCheckDetail.dtable.datagrid('beginEdit', index);
        }
    };
    grid.onLoadSuccess = function () {
        if(CCheckDetail.checkStatus == 0) {//未校正时才需要判断是否显示提示
            var rows = CCheckDetail.dtable.datagrid("getRows");
            var isShow = 0;
            for(var i=0; i<rows.length; i++) {
                if(Number(rows[i].count) != Number(rows[i].curNum)) {
                    isShow = 1;
                    break;
                }
            }
            if(isShow == 1) {
                $("#tips").show();
            }
        }
    };
    grid.loadGrid();
    if(CCheckDetail.checkStatus == 0) {
        CCheckDetail.dtable.datagrid('enableCellEditing');
    }
};
CCheckDetail.dg.getOne = function () {
    var sels = CCheckDetail.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
CCheckDetail.dg.getSels = function () {
    return CCheckDetail.dtable.datagrid('getSelections');
};
CCheckDetail.refresh = function() {
    window.location.reload();
};
// 处理按钮
CCheckDetail.btn = function () {
    var sb = new $yd.SearchBtn($(CCheckDetail.obtn));
    if(CCheckDetail.checkStatus == 0) {
        sb.create('check green', '校正库存', CCheckDetail.correct);
    }

    sb.create('refresh', '刷新', CCheckDetail.refresh);
};

//编辑
CCheckDetail.edit = function () {
    var sel = CCheckDetail.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    CCheckDetail._edit(sel['id'])
};
// 表单预处理
CCheckDetail.preForm = function () {
    new $yd.combobox("checkId").load("/check/select");
    new $yd.combobox("skuId").load("/sku/select");
};
CCheckDetail._edit = function (id) {
    $yd.win.create('编辑盘点单详情', CCheckDetail.uEdit + '?id=' + id).open(function (that, $win) {
            CCheckDetail.preForm();
            $yd.get(CCheckDetail.u + "/" + id, function (data) {
                $win.find('form').form('load', data);
            })
        }, function (that, $win) {
            $yd.form.create($win.find('form')).url(CCheckDetail.u).submit(function () {
                that.close();
                CCheckDetail.refresh();
            });
        }
    );
};
//新增
CCheckDetail.plus = function () {
    var sel = CCheckDetail.dg.getOne();
    var href = CCheckDetail.uEdit;
    if (sel) href += '?pid=' + sel['id'] + '&name=' + sel['name'];
    $yd.win.create('新增盘点单详情', href).open(function (that, $win) {
            CCheckDetail.preForm();
        }, function (that, $win) {
            $yd.form.create($win.find('form')).url(CCheckDetail.u).submit(function () {
                that.close();
                CCheckDetail.refresh();
            });
        }
    );
};
//
CCheckDetail.refresh = function () {
    CCheckDetail.dtable.datagrid('reload');
};

//删除
CCheckDetail.remove = function () {
    $yd.confirm(function () {
        $.get("/cCheck/delete", {checkId: CCheckDetail.checkId}, function (data) {
            $yd.alert(data.message);
        });
    });
};

// 校正库存
CCheckDetail.correct = function () {
    //结束编辑状态
    if (CCheckDetail.editIndex != undefined && CCheckDetail.editIndex != -1) {
        CCheckDetail.dtable.datagrid('endEdit', CCheckDetail.editIndex);
    }

    if (CCheckDetail.checkStatus == 1) {
        $yd.alert("已经校正过");
        return;
    } else if (CCheckDetail.checkStatus == 2) {
        $yd.alert("已作废无法校验");
        return;
    }
    $yd.confirm(function () {
        var rows = CCheckDetail.dtable.datagrid("getRows");
        $.get("/cCheck/correct", {
            checkId: CCheckDetail.checkId,
            details: JSON.stringify(rows)
        }, function (data) {
            if (data.message == "") {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            } else if(data.message == "notNew") {
                $yd.alert("当前库存不是最新，需要刷新页面", function () {
                    window.location.reload();
                });
            } else {
                $yd.alert(data.message);
            }
        });
    });
}

$(function () {
    CCheckDetail.checkStatus = $("#checkStatus").val();

    CCheckDetail.checkId = $("#checkId").val();
    CCheckDetail.dtable = $('#cCheckDetail_table');
    CCheckDetail.obtn = '#cCheckDetail_btn';

    CCheckDetail.dg(); // 数据表格
    CCheckDetail.btn(); // 初始化按钮

    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = function (e) {
        e = window.event || e; // 兼容IE7
        obj = $(e.srcElement || e.target);

        if (!$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
            if (CCheckDetail.editIndex != -1) {
                CCheckDetail.dtable.datagrid('endEdit', CCheckDetail.editIndex);
                CCheckDetail.editIndex = -1;
            }
        }
    };
});